package com.forward.uploadapp.activity;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.forward.uploadapp.BaseActivity;
import com.forward.uploadapp.R;
import com.forward.uploadapp.entity.AppInfo;
import com.forward.uploadapp.util.BmobUtils;
import com.forward.uploadapp.util.ToastUtils;

import java.io.File;
import java.io.Serializable;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class AppInfoActivity extends BaseActivity {

    private AppInfo mAppInfo;
    private int mFromWhich;
    private int mPosition;
    private TextView mCategory;
    private EditText mJson;
    private EditText mTaskId;
    private EditText mAppName;
    private EditText mPackageName;
    private EditText mVersionName;
    private EditText mVersionCode;
    private EditText mDownloadUrl;
    private EditText mIconUrl;
    private EditText mFileSize;
    private EditText mDescrible;
    private EditText mCompany;
    private EditText mType;
    private EditText mStar;

    @Override
    public int getLayoutId() {
        return R.layout.activity_app_info;
    }

    @Override
    public void initView() {
        mCategory = (TextView) findViewById(R.id.category);
        mJson = (EditText) findViewById(R.id.app_json);
        mTaskId = (EditText) findViewById(R.id.task_id);
        mAppName = (EditText) findViewById(R.id.app_name);
        mPackageName = (EditText) findViewById(R.id.package_name);
        mVersionName = (EditText) findViewById(R.id.version_name);
        mVersionCode = (EditText) findViewById(R.id.version_code);
        mDownloadUrl = (EditText) findViewById(R.id.download_url);
        mIconUrl = (EditText) findViewById(R.id.icon_url);
        mFileSize = (EditText) findViewById(R.id.file_size);
        mDescrible = (EditText) findViewById(R.id.describle);
        mCompany = (EditText) findViewById(R.id.company);
        mType = (EditText) findViewById(R.id.type);
        mStar = (EditText) findViewById(R.id.star);
    }

    @Override
    public void initData() {
        mCategory.setText(getString(R.string.category_format, ""));
        mFromWhich = getIntent().getIntExtra("from", 0);
        mPosition = getIntent().getIntExtra("position", -1);
        Serializable appInfo = getIntent().getSerializableExtra("appInfo");
        if (appInfo != null) {
            mAppInfo = (AppInfo) appInfo;
            initLayout();
        }
//        if ((mFromWhich == FROM_GET_JSON_ACTIVITY
//                || mFromWhich == FROM_BMOB_ACTIVITY) && mPosition != -1) {
//            mAppInfo = (AppInfo) appInfo;
//            initLayout();
//        }
    }

    @Override
    public void initListener() {
    }

    public void productJson(View view) {
        updateAppInfo();
        if (mFromWhich == FROM_GET_JSON_ACTIVITY) {
            Intent intent = new Intent(this, GetJsonActivity.class);
            intent.putExtra("appInfo", mAppInfo);
            intent.putExtra("position", mPosition);
            setResult(FROM_APP_INFO_ACTIVITY, intent);
            finish();
        } else {
            if (mAppInfo != null) {
                mJson.setText(mAppInfo.toString());
            }
        }
    }

    public void upload(View view) {
        try {
            if (mAppInfo != null && mAppInfo.getObjectId() != null) {
                updateAppInfo();
                BmobUtils.updateData(mAppInfo, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        Log.i("ljh", "updateData " + e);
                    }
                });
            } else {
                mAppInfo = new AppInfo();
                updateAppInfo();
                BmobUtils.addData(mAppInfo, new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        Log.i("ljh", "addData " + s + " e " + e);
                    }
                });
            }
            Intent intent = new Intent(AppInfoActivity.this, BmobActivity.class);
            setResult(FROM_APP_INFO_ACTIVITY, intent);
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void selectFile(View view) {
        Intent intent = new Intent(this, FileDisplayActivity.class);
        intent.putExtra("from", FROM_APP_INFO_ACTIVITY);
        startActivityForResult(intent, FROM_APP_INFO_ACTIVITY);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FROM_APP_INFO_ACTIVITY) {
            if (resultCode == FROM_FILE_DISPLAY_ACTIVITY) {
                File file = (File) data.getSerializableExtra("selectFile");
                mCategory.setText(getString(R.string.category_format, file.getAbsolutePath()));
                initLayout(file);
            }
        }
    }

    private void initLayout() {
        if (mAppInfo != null) {
            mTaskId.setText(String.valueOf(mAppInfo.getTaskId()));
            mAppName.setText(mAppInfo.getAppName());
            mPackageName.setText(mAppInfo.getPackageName());
            mVersionName.setText(mAppInfo.getVersionName());
            mVersionCode.setText(mAppInfo.getVersionCode());
            mDownloadUrl.setText(mAppInfo.getDownloadUrl());
            mIconUrl.setText(mAppInfo.getIconUrl());
            mFileSize.setText(mAppInfo.getFileSize());
            mDescrible.setText(mAppInfo.getDescrible());
            mCompany.setText(mAppInfo.getCompany());
            mType.setText(mAppInfo.getType());
            mStar.setText(mAppInfo.getStar());
            mJson.setText(mAppInfo.toString());
        }
    }

    private void initLayout(final File file) {
        if (file != null && file.getAbsolutePath().endsWith(".apk")) {

            final PackageInfo packageInfo = getPackageManager().getPackageArchiveInfo(
                    file.getAbsolutePath(), PackageManager.GET_ACTIVITIES);
            BmobUtils.queryDatasByPackageName(packageInfo.packageName, new FindListener<AppInfo>() {
                @Override
                public void done(List<AppInfo> list, BmobException e) {
                    if (e == null) {
                        mAppInfo = list.get(0);
                        initLayout();
                    }
                    if (mAppInfo != null
                            && packageInfo.versionCode < Integer.parseInt(mAppInfo.getVersionCode())) {
                        ToastUtils.toast(AppInfoActivity.this, getString(R.string.current_version_too_low));
                        return;
                    }
                    mPackageName.setText(packageInfo.packageName);
                    mVersionName.setText(packageInfo.versionName);
                    mVersionCode.setText(String.valueOf(packageInfo.versionCode));
                    mDownloadUrl.setText("download/" + file.getName());
                    mFileSize.setText(String.valueOf(file.length()));
                }
            });
        }
    }

    private void updateAppInfo() {
        mAppInfo.setTaskId(Long.parseLong(mTaskId.getText().toString().trim()));
        mAppInfo.setAppName(mAppName.getText().toString());
        mAppInfo.setPackageName(mPackageName.getText().toString().trim());
        mAppInfo.setVersionName(mVersionName.getText().toString());
        mAppInfo.setVersionCode(mVersionCode.getText().toString());
        mAppInfo.setDownloadUrl(mDownloadUrl.getText().toString().trim());
        mAppInfo.setIconUrl(mIconUrl.getText().toString().trim());
        mAppInfo.setFileSize(mFileSize.getText().toString().trim());
        mAppInfo.setDescrible(mDescrible.getText().toString());
        mAppInfo.setCompany(mCompany.getText().toString());
        mAppInfo.setType(mType.getText().toString());
        mAppInfo.setStar(mStar.getText().toString());
        mJson.setText(mAppInfo.toString());
    }
}
